import { resources } from "cc"
import { DataMgr } from "./DataMgr"
import { PoolMgr } from "./PoolMgr"

export class ResMgr {
    public audioMap = {}
    public spriteMap = {}

    private static _ins: any = null

    static getIns<T>(): T {
        if (this._ins === null) {
            this._ins = new this()
        }
        return this._ins
    }

    static get ins() {
        return this.getIns<ResMgr>()
    }

    public async init(resource: any) {
        return new Promise<void>((resolve, reject) => {
            const rate = DataMgr.ins.loadingRange
            resources.loadDir(resource.path, resource.content, (finished: number, total: number) => {
                // 资源加载进度
                if (resource.ratio > 0) DataMgr.ins.loadingRange = rate + resource.ratio * finished / total
            }, (err, assets: any) => {
                if (err) reject && reject()
                let asset: any
                if (resource.type == 'audio') {
                    for (let i = 0; i < assets.length; i++) {
                        asset = assets[i];
                        if (!this.audioMap[asset.name]) this.audioMap[asset.name] = asset
                    }
                }
                if (resource.type == 'prefab') {
                    for (let i = 0; i < assets.length; i++) {
                        asset = assets[i];
                        PoolMgr.ins.setPrefab(asset.data.name, asset)
                    }
                }
                if (resource.type == 'sprite') {
                    for (let i = 0; i < assets.length; i++) {
                        asset = assets[i];
                        if (!this.spriteMap[asset.name]) this.spriteMap[asset.name] = asset
                    }
                }
                resolve && resolve()
            })
        })
    }

    public getAudio(name: string) {
        return this.audioMap[name]
    }

    public getSprite(name: string) {
        return this.spriteMap[name]
    }
}


